const moment = require('moment');
const helper = require('./helper');
// const sqlQuery = require('./mysql-async');
const mysql = require('../core/mysql');
const config = require('../config/environment');

const account = {
  name: config.adminName,
  password: config.adminPassword
};

exports.saveAdminAccount = async function () {
  try {
      let mobileToken = helper.makeMobileToken();
      console.log(helper.verifyAccesstoken('1000|1.9493e0263965241bef76ac745407d369b0c2b68fca94275e23a259c58af9d07d.900.1522649289307-1a26b3e825174e73960a2e0d71fd6cce'))
      console.log(mobileToken.substr(0,8) + mobileToken.substr(9,4)
          + mobileToken.substr(14,4) + mobileToken.substr(19,4) + mobileToken.substr(24,12));
    let salt = helper.makeSalt();
    let hashedPassword = helper.encryptPassword(account.password, salt);

    let selectAdmin = await mysql.query(`SELECT * FROM manager WHERE role_id=0`);
    if (selectAdmin.length > 0) {
      let id = selectAdmin[0].manager_id;
      await mysql.query(`UPDATE manager SET hash_password = ?,salt = ? WHERE manager_id = ?`, [hashedPassword, salt,id]);
    } else {
      let newAdmin = {
        user_name: account.name,
        hash_password: hashedPassword,
        salt: salt,
        role_id: 0,
        create_time: moment().format('YYYY-MM-DD HH:mm:ss')
      };
      await mysql.query(`INSERT INTO user SET ?`, newAdmin);
    }
  } catch (error) {
    console.log('saveAdminAccount', error);
  }
};
